package com.google.code.msgbooster.batch.detector.extension;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.Validate;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.InvalidXPathException;
import org.dom4j.io.SAXReader;

import com.google.appengine.api.datastore.Link;
import com.google.code.msgbooster.batch.detector.Clip;
import com.google.code.msgbooster.batch.detector.Core;
import com.google.code.msgbooster.model.extension.Guide;

public final class XML extends Core {

	@SuppressWarnings("unchecked")
	@Override
	protected List<Clip> resolve(InputStream inputStream, Guide guide)
			throws Exception {
		List<Clip> clips = new ArrayList<Clip>();
		SAXReader saxReader = new SAXReader();
		Document doc = saxReader.read(new InputStreamReader(inputStream,
				getDefaultCharset()));
		List<Element> nodes = doc.selectNodes(guide.getClue());
		for (Element node : nodes) {
			String content = node.elementText(guide.getContentElement());
			String resource = node.elementText(guide.getLinkElement());
			Clip clip = new Clip();
			clip.setContent(content);
			try {
				Validate.notEmpty(resource);
				clip.setResource(new Link(resource));
			} catch (IllegalArgumentException e) {
				clip.setResource(null);
			}
			try {
				Validate.notNull(guide.getFixedLink());
				clip.setFixedLink(guide.getFixedLink());
			} catch (IllegalArgumentException e) {
				clip.setFixedLink(null);
			}			
			clips.add(clip);
		}
		return clips;
	}

	@Override
	protected boolean isReconnect(Exception exception, boolean result) {
		if (InvalidXPathException.class.isInstance(exception)) {
			result = false;
		} else {
		}
		return result;
	}

}
